import { FormGroup, FormControl, AbstractControl, ValidationErrors } from '@angular/forms';
import { RegExs } from './regex';
// form helper

export function formGroupToFormData(formGroup: FormGroup) {
	const data = new FormData();
	for (const [key, value] of Object.entries(formGroup.value)) {
		if (value instanceof Array) {
			value.forEach(v => data.append(key, v));
		} else if (value) {
			data.set(key, value as any);
		}
	}
	return data;
}

export function formGroupToFormRawData(formGroup: FormGroup) {
	const data = new FormData();
	for (const [key, value] of Object.entries(formGroup.getRawValue())) {
		if (value instanceof Array) {
			value.forEach(v => data.append(key, v));
		} else if (value) {
			data.set(key, value as any);
		}
	}
	return data;
}

export function markAllAsTouched(formGroup: FormGroup) {
	Object.values(formGroup.controls).forEach(control => {
		control.markAsTouched();
		if (control instanceof FormGroup) {
			markAllAsTouched(control);
		}
	});
	const err = firstInvalid(formGroup);
	if (err.length > 0) {
		console.error('form invalid', err);
	}
}

export function firstInvalid(formGroup: FormGroup): string[] {
	for (const name of Object.keys(formGroup.controls)) {
		if (formGroup.controls[name].invalid) {
			return [name];
		}
	}
	return [];
}
// confirm password and set error to confirm control
export function confirmPassword(opt = { password: 'password', confirm: 'confirm' }) {
	return (group: FormGroup): null => {
		const password = group.get(opt.password);
		const confirm = group.get(opt.confirm);
		if (password && confirm && password.value != confirm.value) {
			confirm.setErrors({ confirm: true });
		} else if (confirm.errors) {
			delete confirm.errors['confirm'];
			confirm.setErrors(confirm.errors);
		}
		return;
	};
}

export function regexForbidSpecialChars(col = 'full_name') {
	return (group: FormGroup): null => {
		const fullName = group.get(col)	
		if (fullName.value.match(RegExs.NOCHARACTERS)) {
			fullName.setErrors({ nocharacters: true });
		}	else if (fullName.errors) {
			delete fullName.errors['nocharacters'];
			fullName.setErrors(fullName.errors);
		}
		return;
	}
}
